<?php
// +----------------------------------------------------------------------
// | PHP [ JUST YOU ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2017 http://www.jyphp.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: FlyingPig <flyingpigfp@163.com>
// +----------------------------------------------------------------------

namespace App\Http\Controllers;


use App\Common\Logger;
use App\Common\Sql;
use App\Exceptions\ApiException;
use App\Logic\PayCallBackLogic;
use Illuminate\Support\Facades\DB;

class ApplePay extends Base
{

    public function logic()
    {

        if (!isset($this->param['goods_id'])) {
            throw new ApiException('goods_id must be needed');
        }
//        $receipt_data = file_get_contents("php://input");
        $receipt_data = $this->param['receipt'];
        if (!isset($receipt_data)) {
            throw new ApiException('post receipt_data must be needed', 320);
        } else if (strlen($receipt_data) < 30) {
            throw new ApiException('receipt_data error.', 320);
        }
        $uid      = $this->uid;
        $goods_id = $this->param['goods_id'];

        DB::beginTransaction();
        try {
            //判断本地订单是否已经完成。
            $order_id = $this->createOrderId($receipt_data);
            $row      = Sql::select('t_pay_info', [['order_id', $order_id]], ['order_status']);
            if (count($row)) {
                if ((int)($row[0]['order_status']) == 1) {//订单已经完成，无需重复
                    throw new ApiException('订单已经完成,无需重复处理', 320);
                }

                if ((int)($row[0]['order_status']) < 1) {//订单没有完成，重新下单
                    $html            = $this->acurl($receipt_data);
                    $data            = json_decode($html, 1);
                    $data['sandbox'] = 0;
                    //如果是沙盒数据 则验证沙盒模式
                    if ($data['status'] == '21007') {
                        //请求验证
                        $html            = $this->acurl($receipt_data, $sandbox = 0);
                        $data            = json_decode($html, 1);
                        $data['sandbox'] = 1;
                    }
                    //返回
                    $ret_arr = array();
//                    if ($data['sandbox']) {
//                        $ret_arr['sandbox'] = 1;
//                    }

                    if ($data['status'] == 0) {
                        Logger::instance()->error('苹果支付下单响应(成功)', $html);
                        PayCallBackLogic::instance()->handle($order_id, '苹果支付:' . $order_id);
                        return $this->returnData($ret_arr);
                    } else {
                        Logger::instance()->error('苹果支付下单响应(失败)', $html);
                        PayCallBackLogic::instance()->updatePay($order_id,'苹果支付下单响应失败');
                    }
                }
            } else {
                //没有数据，重新插入订单
                $payinfo                 = array();
                $payinfo['order_id']     = $order_id;
                $payinfo['pay_type']     = 3;
                $payinfo['uid']          = $uid;
                $payinfo['order_status'] = 0;
                $payinfo['goods_id']     = $goods_id;
                $payinfo['goods_type']   = $this->param['goods_type'];

                $payinfo['receipt_data'] = $receipt_data;
                $payinfo['create_time']  = date('Y-m-d H:i:s', time());
                $ret                     = DB::table('t_pay_info')->insertGetId($payinfo);

                //下单
                $html            = $this->acurl($receipt_data);
                $data            = json_decode($html, 1);
                $data['sandbox'] = 0;
                //如果是沙盒数据 则验证沙盒模式
                if ($data['status'] == '21007') {
                    //请求验证
                    $html            = $this->acurl($receipt_data, $sandbox = 0);
                    $data            = json_decode($html, 1);
                    $data['sandbox'] = 1;
                }

                $ret_arr = array();
//                if ($data['sandbox']) {
//                    $ret_arr['sandbox'] = 1;
//                }
                if ($data['status'] == 0) {
                    Logger::instance()->error('苹果支付下单响应(成功)', $html);
                    PayCallBackLogic::instance()->handle($ret, '苹果支付:' . $order_id);
                    return $this->returnData($ret_arr);
                } else {
                    Logger::instance()->error('苹果支付下单响应(失败)', $html);
                    PayCallBackLogic::instance()->updatePay($order_id,'苹果支付下单响应失败');
                }

            }
        } catch (\Exception $exception) {
            DB::rollBack();
            Logger::instance()->setErrorLog($exception);
        }

    }

    /**
     * 21000 App Store不能读取你提供的JSON对象
     * 21002 receipt-data域的数据有问题
     * 21003 receipt无法通过验证
     * 21004 提供的shared secret不匹配你账号中的shared secret
     * 21005 receipt服务器当前不可用
     * 21006 receipt合法，但是订阅已过期。服务器接收到这个状态码时，receipt数据仍然会解码并一起发送
     * 21007 receipt是Sandbox receipt，但却发送至生产系统的验证服务
     * 21008 receipt是生产receipt，但却发送至Sandbox环境的验证服务
     */
    private function acurl($receipt_data, $sandbox = 0)
    {
        //小票信息
        $POSTFIELDS = array("receipt-data" => $receipt_data);
        $POSTFIELDS = json_encode($POSTFIELDS);

        //正式购买地址 沙盒购买地址
        $url_buy     = "https://buy.itunes.apple.com/verifyReceipt";
        $url_sandbox = "https://sandbox.itunes.apple.com/verifyReceipt";
        $url         = $sandbox ? $url_sandbox : $url_buy;

        //简单的curl
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $POSTFIELDS);
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
    }


    private function createOrderId($receipt_data)
    {
        $seed = md5($receipt_data);
        $pwd  = '';
        for ($i = 0; $i < 30; $i++) {
            $pwd .= $seed[$i];
        }
        return $pwd;
    }

}